package com.lky.web.useradmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lky.dto.UserExecution;
import com.lky.entity.User;
import com.lky.service.UserService;
import com.lky.util.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.RequestWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Lenovo on 2018/1/16.
 */

@Controller
@RequestMapping("/useradmin")
public class UserManagementController {
    @Autowired
    private UserService userService;
    @RequestMapping(value="/registeruser")
    @ResponseBody
    private Map<String,Object> registerUser(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        //获取名为userStr的参数
        String userStr = HttpServletRequestUtil.getString(request,"userStr");
        //String username= HttpServletRequestUtil.getString(request,"username");
        //正则表达式，判断手机号是否合理
        String p = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0-9]))\\d{8}$";
        //验证身份证号码是否合法
        String card = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
        ObjectMapper mapper = new ObjectMapper();
        User user = null;
        try {
            //将json字符串转为user对象
            user = mapper.readValue(userStr,User.class);
        }
        catch (Exception e) {
            modelMap.put("success",false);
            modelMap.put("errMsg",e.toString());
            return modelMap;
        }
        //用户合法性判断
        if(user != null && user.getUserName()!="" && user.getuName()!="" && user.getUserPassword()!="" && user.getPhone()!="" && user.getUserCardId()!="" && user.getUserAddr()!=""){
            int queryNum = userService.queryUserByName(user.getUserName()).size();
            String str = user.getPhone();
            boolean mp = Pattern.matches(p,user.getPhone());
            boolean cp = Pattern.matches(card,user.getUserCardId());
            if(queryNum == 0 && mp && cp){
                userService.addUser(user);
                modelMap.put("success",true);
                return modelMap;
            }else{
                modelMap.put("success",false);
                modelMap.put("errMsg","用户信息不合法");
                return modelMap;
            }

        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入用户信息");
            return modelMap;
        }

    }

    /*RequestMapping(value = "/getuserlist",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getUserList(){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        List<User> userList = new ArrayList<User>();
        try{
            userList = userService.queryUser();
            modelMap.put("userList",userList);
            modelMap.put("success",true);
        }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
        }
        return modelMap;

    }*/


    /**
     * 获取用户列表信息
     */
    @RequestMapping(value = "/getuserlist",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getUserList(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        //List<User> userList = new ArrayList<>();

        int pageIndex = HttpServletRequestUtil.getInt(request,"pageIndex");
        int pageSize = HttpServletRequestUtil.getInt(request,"pageSize");
        try{
            //userList = userService.queryUser();
            UserExecution ue = userService.getUserList(pageIndex,pageSize) ;
            int n = ue.getCount();
            modelMap.put("userList",ue.getUserList());
            modelMap.put("num",n);
            modelMap.put("success",true);
        }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
        }
        return modelMap;

    }

    @RequestMapping(value = "/getuserbyid", method = RequestMethod.GET)
    @ResponseBody
    //通过用户id获取用户
    private Map<String, Object> getUserById(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        Integer userId = HttpServletRequestUtil.getInt(request, "userId");
        if (userId > -1) {
            try {
               User user = userService.getByUserId(userId);
                modelMap.put("user", user);
                modelMap.put("success", true);
            } catch (Exception e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
            }
        } else {

            modelMap.put("success", false);
            modelMap.put("errMsg", "empty userId");
        }
        return modelMap;
    }

    /*@RequestMapping(value = "/deluserbyid", method = RequestMethod.GET)
    public String delUser(@RequestParam("userId") Integer userId){
        System.out.println(userId);
        userService.delByUserId(userId);
        return "redirect:/useradmin/userlist";
    }*/

    //通过用户id删除用户
    @RequestMapping(value = "/deluserbyid", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> delUser(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        Integer userId = HttpServletRequestUtil.getInt(request, "userId");
        int pageLast = HttpServletRequestUtil.getInt(request,"pageLast");
        int page = HttpServletRequestUtil.getInt(request,"page");
        if (userId > -1) {
            try {
                userService.delByUserId(userId);
                if(pageLast==1){
                    page = page-1;
                }
                int pageIndex = page;
                int pageSize = 5;
                UserExecution ue = userService.getUserList(pageIndex,pageSize) ;
                modelMap.put("userList",ue.getUserList());
                modelMap.put("success", true);
            } catch (Exception e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "empty userId");
        }
        return modelMap;
    }




    @RequestMapping(value="modifyuser")
    @ResponseBody
    //修改用户信息
    private Map<String,Object> upDaterUser(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        String userStr = HttpServletRequestUtil.getString(request,"userStr");
        //String username= HttpServletRequestUtil.getString(request,"username");
        //正则表达式，验证手机号与身份证号的合法性
        String p = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0-9]))\\d{8}$";
        String card = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
        ObjectMapper mapper = new ObjectMapper();
        User user = null;
        try {
            user = mapper.readValue(userStr,User.class);
        }
        catch (Exception e) {
            modelMap.put("success",false);
            modelMap.put("errMsg",e.toString());

            return modelMap;
        }
        if(user != null && user.getuName()!="" && user.getUserPassword()!="" && user.getPhone()!="" && user.getUserCardId()!="" && user.getUserAddr()!=""){
            Integer userId = userService.queryUserByName(user.getUserName()).get(0).getUserId();
            user.setUserId(userId);
            String str = user.getPhone();
            boolean mp = Pattern.matches(p,user.getPhone());
            boolean cp = Pattern.matches(card,user.getUserCardId());
            if(mp && cp){
                userService.updateUser(user);
                modelMap.put("success",true);
                return modelMap;
            }else{
                modelMap.put("success",false);
                modelMap.put("errMsg","用户信息不合法");
                return modelMap;
            }

        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入用户信息");
            return modelMap;
        }

    }

}
